package ru.adhoc.truealarm.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import ru.adhoc.truealarm.R;
import ru.adhoc.truealarm.alarmreceiver.AlarmManagerBroadcastReceiver;
import ru.adhoc.truealarm.db.DbHelper;
import ru.adhoc.truealarm.notification.NfHelper;
import ru.adhoc.truealarm.player.SoundPlayer;
import ru.adhoc.truealarm.time.TimeHelper;
import ru.adhoc.truealarm.utils.Util;

import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;


/**
 * Created by Малюгин Сергей on 01.07.13.
 */
public class SetAlarm extends Activity {

    private TimePicker tpTime;
    private DbHelper DbHelper;
    private String LOG_TAG = "My";
    private int type_set;
    private Cursor cursorMelody;
    private TextView tvMelody2;
    private String soundURI;
    private Context context;
    private CheckBox chbVibro;
    private TextView tvDescription;
    private String strRepeat = "";
    private String storedRep;
    private TextView tvInt;
    private boolean is24HourFormat;
    private Uri defaultUri;
    private LinearLayout llParentSet;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_alarm);

        type_set = getIntent().getExtras().getInt("type_set"); // 0 или айди текущего будильника
        DbHelper = DbHelper.getInstance(this);
        chbVibro = (CheckBox)findViewById(R.id.chbVibro);
        tvMelody2= (TextView)findViewById(R.id.tvMelody2);
        context = this.getApplicationContext();
        tpTime = (TimePicker)findViewById(R.id.tpTime);
        tvDescription =(TextView)findViewById(R.id.tvDescription);
        tvInt = (TextView)findViewById(R.id.tvInt);
        is24HourFormat = DateFormat.is24HourFormat(this);
        defaultUri = Uri.parse("android.resource://ru.adhoc.truealarm/" + R.raw.nature);
        llParentSet = (LinearLayout)findViewById(R.id.ll_parent_set);

        Util.getInstance(context).setTheme(llParentSet);

        //Заполняем при открытии из базы...чтоб не стирать уже записанные
        SQLiteDatabase db = DbHelper.getReadableDatabase();
        try {
            strRepeat = DbHelper.getRepDays(db, type_set);
        }
        finally {
            if(db != null)
                db.close();
        }

        SQLiteDatabase db1 = DbHelper.getReadableDatabase();
        try{
            Uri URI = DbHelper.getAlarmSoundURI(db1, type_set);
            if(URI.toString().equals(defaultUri.toString())){
                tvMelody2.setText("nature.ogg");
            }
            soundURI = URI.toString();
        }
        finally {
            if(db1 != null)
                db1.close();
        }

        if(is24HourFormat)
            tpTime.setIs24HourView(true);
        else
            tpTime.setIs24HourView(false);

        // если параметр = 0 тогда это создание нового будильника иначе это его id
        if (type_set == 0)setCurrentTime();
        else setExistTime();
    }

//set on time picker alarm time
    private void setExistTime(){

        SQLiteDatabase db = DbHelper.getWritableDatabase();
        Cursor c = DbHelper.getOnesAlarm(db, type_set);
        Long time = 0L;
        String strUri = "";
        String strComm = "";
        int vibrate = 0;
        String strRep = "";
        int interval = 0;

        if(c.moveToFirst()){
            time = c.getLong(c.getColumnIndex("time"));
            strComm = c.getString(c.getColumnIndex("comment"));
            strUri = c.getString(c.getColumnIndex("sounduri"));
            vibrate = c.getInt(c.getColumnIndex("vibrate"));
            strRep = c.getString(c.getColumnIndex("repdays"));
            interval = c.getInt(c.getColumnIndex("interval"));
        }
        c.close();

        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(time);
        tpTime.setCurrentHour(cl.get(Calendar.HOUR_OF_DAY));
        tpTime.setCurrentMinute(cl.get(Calendar.MINUTE));

        //устанавливаем значение интервала откладывания в текстовое поле настроек
        tvInt.setText(Integer.toString(interval));

        //Если поле комента пустое то пишем комент по умолчанию
        if(strComm.length() != 0)
            tvDescription.setText(strComm);
        else
            tvDescription.setText(getString(R.string.Alarm) +" "+ DbHelper.getAlarms(db).getCount());

        if(db != null)
            db.close();

        if(strUri.equals(defaultUri.toString()) || strUri.length() == 0){
            tvMelody2.setText("nature.ogg");
        }
        else {
            //если звука нет на флешке то мы получим пустое имя
            String name = new File(getRealPathFromURI(Uri.parse(strUri))).getName();
            if(name.length() == 0)
                tvMelody2.setText("nature.ogg");
            else
                tvMelody2.setText(new File(getRealPathFromURI(Uri.parse(strUri))).getName());
        }

        if(vibrate == 1)
            chbVibro.setChecked(true);
        else chbVibro.setChecked(false);



        TextView tvRepDays = (TextView) findViewById(R.id.tvRepDays);
        tvRepDays.setText(Util.getInstance(context).createRepDaysString(strRep));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_setalarm, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.actAdd){
            if(type_set == 0)addNewAlarm();
            else editTimeAlarm();
        }
        else
            finish();

        return super.onOptionsItemSelected(item);
    }

//set current time on time picker
    private void setCurrentTime(){
        int hour = 0;
        int min = 0;
        tpTime.setCurrentHour(hour);
        tpTime.setCurrentMinute(min);
        chbVibro.setChecked(true);
        tvInt.setText("5");

        TextView tvRepDays = (TextView) findViewById(R.id.tvRepDays);
        tvRepDays.setText(Util.getInstance(context).createRepDaysString(""));

    }

//return time on time picker in msec
    private Long getAlarmTimeMSEC(){
        Calendar cl = Calendar.getInstance();
        cl.set(Calendar.HOUR_OF_DAY,0);
        cl.set(Calendar.MINUTE,0);
        cl.set(Calendar.SECOND,0);
        cl.set(Calendar.MILLISECOND,0);
        /*Время там хранится только в 12 часововм формате по этому приводим его к
        00 часам вычитая 12 часов
         */
        return (tpTime.getCurrentHour()*60*60*1000) + (tpTime.getCurrentMinute()*60*1000) +
                cl.getTimeInMillis();
    }

    //create new alarm in db
    private void addNewAlarm(){

        String comm = tvDescription.getText().toString();
        Long time = getAlarmTimeMSEC();
        Long actTimeNew = TimeHelper.getInstance(context).getActualTimeForAlarmByTime(time, strRepeat);

        SQLiteDatabase db = DbHelper.getWritableDatabase();

        try{

            int count  = DbHelper.getAlarms(db).getCount();

            //create in db new alarm
            long id = DbHelper.insertAlarm(db, actTimeNew, count+1, 1, comm, soundURI,
                    chbVibro.isChecked(), strRepeat, Integer.parseInt(String.valueOf(tvInt.getText())));
            //run receiver
            AlarmManagerBroadcastReceiver alarm = new AlarmManagerBroadcastReceiver();
            alarm.SetAlarm(context,actTimeNew, (int)id);
            //show toast
            TimeHelper.getInstance(context).showAlarmToast(actTimeNew);

        } catch (SQLException e) {
            Log.e(LOG_TAG, "Error while adding alarm", e);
        } finally {
            if(db != null)
                db.close();
        }

        //show alarm notification
        NfHelper.getInstance(this).showNotificationService(0L, false);

        finish();
    }

//refresh existing alarm in db
    private void editTimeAlarm(){

        Long time = getAlarmTimeMSEC();
        String comm = tvDescription.getText().toString();
        Long actTimeNew = TimeHelper.getInstance(context).getActualTimeForAlarmByTime(time, strRepeat);

//stop alarm receiving
            AlarmManagerBroadcastReceiver alarm = new AlarmManagerBroadcastReceiver();
            alarm.CancelAlarm(context,type_set);

//run new alarm receiving
            alarm.SetAlarm(context,actTimeNew, type_set);

//show toast
            TimeHelper.getInstance(context).showAlarmToast(actTimeNew);

//Пишем в базу новое время будильника новй комментарий, ури
        SQLiteDatabase db1 = DbHelper.getWritableDatabase();
        try {
            DbHelper.setNewTime(db1,type_set, actTimeNew, comm, chbVibro.isChecked(), soundURI,
                    strRepeat, Integer.parseInt(String.valueOf(tvInt.getText())));
        } catch (SQLException e) {
            Log.e(LOG_TAG, "Error while editing time alarm", e);
        } finally {
            if(db1 != null)
                db1.close();
        }

//Врубаем обратно свичер
        SQLiteDatabase db2 = DbHelper.getWritableDatabase();
        try {
            DbHelper.setSwitch(db2, type_set, 1);
        }
        finally {
            if(db2 != null)
                db2.close();
        }

//обновляем нотификацию
        NfHelper.getInstance(this).showNotificationService(0L, false);

        finish();
    }

// click on text view sound file name
    public void melodyClick(View view){
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        cursorMelody = contentResolver.query(uri, null, null, null, null);

        if(cursorMelody != null){
            if(cursorMelody.getCount() == 0)
                Toast.makeText(context, getResources().getText(R.string.nomediatoast), Toast.LENGTH_SHORT).show();
            else
                showDialogSelectMelody(view);
        }
        else {
            Toast.makeText(context, getResources().getText(R.string.nomediatoast), Toast.LENGTH_SHORT).show();
        }
    }

//showing dialog to choose sound file
    private void showDialogSelectMelody(View view) {

        final String[] path = new String[1];
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.ChooseAlarm);
        builder.setSingleChoiceItems(cursorMelody, -1, "title", new DialogInterface.OnClickListener()
       {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ListView lv = ((AlertDialog)dialogInterface).getListView();
                    if (cursorMelody.moveToPosition(lv.getCheckedItemPosition())){
                        int idColumn = cursorMelody.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
                        Long thisId = cursorMelody.getLong(idColumn);
                        Uri DATA_URI = ContentUris
                                .withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, thisId);
                        path[0] = getRealPathFromURI(DATA_URI);
                        soundURI = DATA_URI.toString();
//начинаем играть выбранную мелодию
                        SoundPlayer sp = SoundPlayer.getInstance(context);
                        sp.playSound(DATA_URI, type_set, false);
                    }
            }
        });

        builder.setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //Пишем в базу если была чекнута какая либо из строк
                if(!(((AlertDialog)dialog).getListView().getCheckedItemPosition() == -1)){
                    tvMelody2.setText(new File(path[0]).getName());
                }
                else
                {
                    tvMelody2.setText("nature.ogg");
                    soundURI = defaultUri.toString();
                }
                //отключаем воспроизведеине при подтверждении выбора или отмены
                SoundPlayer.getInstance(context).stopPlaySound();
            }
        });
        builder.setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
//отключаем воспроизведеине при подтверждении выбора или отмены
                SoundPlayer.getInstance(context).stopPlaySound();
            }
        });
        AlertDialog AD = builder.create();
        AD.show();
    }

//return real file path by uri
    private String getRealPathFromURI(Uri contentUri) {
        Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
        if(cursor.moveToFirst()){
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            String realPath = cursor.getString(idx);
            cursor.close();
            return realPath;
        }
        else {
            cursor.close();
            return "";
        }
    }

    public void clickRepeat(View view){
        showRepeatDialog();
    }

    private void showRepeatDialog(){
        final ArrayList mSelectedItems = new ArrayList();
        boolean[] checkedItems = new boolean[7];
        String strRepDays;

        if(strRepeat.length() == 0 && storedRep == null){

            SQLiteDatabase db = DbHelper.getReadableDatabase();
            try {
                strRepDays = DbHelper.getRepDays(db, type_set);
            }
            finally {
                if(db != null)
                    db.close();
            }

        }
        else
            strRepDays = strRepeat;

        for (int i = 0; i <= 6; i++){
            if(strRepDays.indexOf(Integer.toString(i)) != -1){
                checkedItems[i] = false;
                mSelectedItems.add(i);
            }
            else
                checkedItems[i] = true;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.repeatDays)
                .setMultiChoiceItems(R.array.days, checkedItems,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which,
                                                boolean isChecked) {
                                if (!isChecked) {
                                    mSelectedItems.add(which);
                                } else if (mSelectedItems.contains(which)) {
                                    mSelectedItems.remove(Integer.valueOf(which));
                                }
                            }
                        })
                .setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        if (mSelectedItems.size() == 7) {
                            Toast.makeText(context,R.string.repeatToast, Toast.LENGTH_SHORT).show();
                            return;
                        }

                        strRepeat = "";
                        for (int i = 0; i < mSelectedItems.size(); i++) {
                            strRepeat = strRepeat + mSelectedItems.get(i);
                        }
                        storedRep = strRepeat;
                        TextView tvRepDays = (TextView) findViewById(R.id.tvRepDays);
                        tvRepDays.setText(Util.getInstance(context).createRepDaysString(storedRep));

                    }
                })
                .setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        AlertDialog AD = builder.create();
        AD.show();
    }

    public void setDescription(final View view){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final EditText input = new EditText(this);
        input.setHint(R.string.Comment);
        builder.setTitle(R.string.descriptionDialogTitle);
        builder.setView(input);

        String currentDescription = tvDescription.getText().toString();

        if(currentDescription.length() != 0)
            input.setText(currentDescription);

        builder.setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
               String result  = input.getText().toString();
                if(result.length() == 0){

                    SQLiteDatabase db = DbHelper.getWritableDatabase();
                    try {
                        tvDescription.setText(getString(R.string.Alarm) +" "+ DbHelper.getAlarms(db).getCount());
                    }
                    finally {
                        if(db != null)
                            db.close();
                    }

                }
                else
                    tvDescription.setText(input.getText().toString());
            }
        });
        builder.setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });
        AlertDialog AD = builder.create();
        AD.show();
    }

    public void clickResetAlarm(View view){
        setResetAlarm();
    }

    private void setResetAlarm(){

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.enterTimeReset);

        final SeekBar sb = new SeekBar(this);
        sb.setMax(30);

        //Проверяем текущий интервал, если отличен от интервала по умолчанию ставим его на сик баре
        int currentInt = Integer.parseInt(String.valueOf(tvInt.getText()));
        if(currentInt != 5){
            sb.setProgress(currentInt);
            builder.setMessage(String.valueOf(tvInt.getText() + " " + getResources().getString(R.string.minutes)));
        }
        else{
            sb.setProgress(5);
            builder.setMessage("5 " + getResources().getString(R.string.minutes));
        }

        builder.setView(sb);

        builder.setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                int progress = sb.getProgress();
                TextView tv = (TextView)findViewById(R.id.tvInt);
                if(progress != 0)
                    tv.setText(String.valueOf(progress));
                else
                    tv.setText("1");
            }
        });

        builder.setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });

        final AlertDialog AD = builder.create();

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
                AD.setMessage(String.valueOf(progress) + " " + getResources().getString(R.string.minutes));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        AD.show();
    }

    public void checkBoxVibroPress(View view){
        if(chbVibro.isChecked())
            chbVibro.setChecked(false);
        else
            chbVibro.setChecked(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Util.getInstance(context).setTheme(llParentSet);
    }

}
